package com.itheima.web.controller.store;

import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.itheima.core.BaseServlet;
import com.itheima.domain.store.Company;
import com.itheima.service.store.CompanyService;
import com.itheima.service.store.impl.CompanyServiceImpl;
import com.itheima.utils.BeanUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/store/company/*")
public class CompanyServlet extends BaseServlet {
    private CompanyService companyService = new CompanyServiceImpl();

    /**
     * 跳转到列表页面
     */
    public String list(HttpServletRequest request, HttpServletResponse response) throws Exception {

        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");

        if (StringUtil.isEmpty(pageNum)) {
            pageNum = "1";
        }
        if (StringUtil.isEmpty(pageSize)) {
            pageSize = "5";
        }

        PageInfo<Company> companyPageInfo = companyService.queryPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));

        request.setAttribute("page", companyPageInfo);
        return "/WEB-INF/pages/store/company/list.jsp";
    }

    public String toAdd(HttpServletRequest request, HttpServletResponse response) throws Exception {
        return "/WEB-INF/pages/store/company/add.jsp";
    }

    public String save(HttpServletRequest request, HttpServletResponse response) throws Exception{
        Company company = BeanUtil.fillBean(request, Company.class, "yyyy-MM-dd");
        companyService.save(company);
        return "/store/company/list";
    }

    public String delete(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String[] ids = request.getParameterValues("id");
        for (String id : ids) {
            companyService.deleteById(id);
        }
        return "/store/company/list";
    }

    public String toEdit(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String id = request.getParameter("id");
        Company byId = companyService.findById(id);
        request.setAttribute("company",byId);
        return "/WEB-INF/pages/store/company/update.jsp";
    }

    public String edit(HttpServletRequest request, HttpServletResponse response)throws Exception{
        /*1.获取表单数据*/
        Company company = BeanUtil.fillBean(request, Company.class, "yyyy-MM-dd");

        /*2.调用se-08rvice*/
        companyService.update(company);

        /*3.页面跳转*/
        return "/store/company/list";
    }
}